<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 中试平台信息 -->
          <div class="project-part">
            <div class="project-part-title">
              中试平台信息
            </div>

            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="平台名称"
                  prop="platformName"
                >
                  <el-input
                    v-model="basicForm.platformName"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="运营主体">
                  <el-input
                    v-model="basicForm.operationMain"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="所属行业">
                  <!-- <el-select
                    placeholder="请选择"
                    v-model="basicForm.industryBelong"
                    clearable
                    :disabled="isDetail"
                  >
                    <el-option
                      v-for="item in industryPlatTypeOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select> -->
                  <el-input
                    v-model="basicForm.industryBelong"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="建设运营模式">
                  <el-input
                    v-model="basicForm.buildOperationModule"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <!-- <el-form-item label="建设状态">
                  <el-select
                    placeholder="请选择"
                    v-model="basicForm.buildStatus"
                    clearable
                    :disabled="isDetail"
                  >
                    <el-option
                      v-for="item in constructionStatusOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item> -->
                <el-form-item label="项目类型">
                  <el-input
                    v-model="basicForm.buildStatus"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="建设周期">
                  <!-- <el-date-picker
                    v-model="basicForm.buildEndTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker> -->
                  <el-input
                    v-model="basicForm.buildEndTime"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预计建成时间">
                  <el-date-picker
                    v-model="basicForm.planBuildTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="实际建成时间">
                  <el-date-picker
                    v-model="basicForm.actuallyBuildTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="服务合同金额(万元)">
                  <el-input
                    v-model="basicForm.contractMoney"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="计划完成投资额(万元)">
                  <el-input
                    v-model="
                      basicForm.planCompleteInvestment
                    "
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="已完成投资额(万元)">
                  <el-input
                    v-model="
                      basicForm.hasCompleteInvestment
                    "
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="联系人及方式">
                  <el-input
                    v-model="basicForm.contract"
                    placeholder="如李某某，13800138000"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="成果介绍">
                  <el-input
                    v-model="basicForm.resultContent"
                    placeholder="请输入"
                    type="textarea"
                    :rows="3"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="关联项目">
                  <el-select
                    placeholder="请选择"
                    v-model="basicForm.projectBaseInfoId"
                    clearable
                    filterable
                    :disabled="isDetail"
                  >
                    <el-option
                      v-for="item in projectBaseInfoOptions"
                      :key="item.pkid"
                      :label="item.name"
                      :value="item.pkid"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 图片上传 -->
          <div class="project-part">
            <div class="project-part-title">平台图片</div>
            <el-form-item label="">
              <el-upload
                class="upload-image"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleChangeImage"
                :on-remove="handleRemoveImage"
                :on-preview="handlePreviewImage"
                :show-file-list="true"
                :file-list="fileList"
                v-if="!isDetail"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"
                  ><div class="icon-text">上传图片</div></i
                >
                <div class="el-upload__tip" slot="tip">
                  支持格式: .jpg.png，单个文件不能超过5MB
                </div>
              </el-upload>

              <el-dialog
                :visible.sync="previewVisible"
                width="50%"
                v-if="!isDetail"
              >
                <img
                  :src="previewImage"
                  alt="预览"
                  style="width: 100%"
                />
              </el-dialog>
              <el-image
                v-for="item in fileList"
                :preview-src-list="previewImageList"
                v-if="isDetail"
                :key="item.url"
                :src="item.url"
                class="image"
              >
              </el-image>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  addCenterPlatform,
  uploadFileById,
  queryConstructionProject
} from '@/api/dataManagement'
import {
  industryPlatTypeOptions,
  constructionStatusOptions
} from '@/utils/project/data'
import { STATIC_FILE_URL } from '@/api/config.js'
import dayjs from 'dayjs'

export default {
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        platformName: '',
        operationMain: '',
        industryBelong: '',
        buildOperationModule: '',
        buildStatus: '',
        planCompleteTime: '',
        buildStartTime: '',
        planCompleteInvestment: '',
        buildEndTime: '',
        hasCompleteInvestment: '',
        planBuildTime: '',
        actuallyBuildTime: '',
        contractMoney: '',
        contract: '',
        resultContent: '',
        picture: '',
        projectBaseInfoId: ''
      },
      basicRules: {
        platformName: [
          {
            required: true,
            message: '请输入平台名称',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      props: { multiple: true },
      uploadFileList: [],
      previewImage: '',
      previewVisible: false,
      previewImageList: [],
      fileList: [],
      projectBaseInfoOptions: []
    }
  },
  computed: {
    titles() {
      return [this.$route.query.title || '中试平台']
    },
    industryPlatTypeOptions() {
      return industryPlatTypeOptions
    },
    constructionStatusOptions() {
      return constructionStatusOptions
    },
    pkid() {
      return this.$route.query.pkid
    },
    isDetail() {
      return this.$route.query.isDetail === 'true'
    },
    isEdit() {
      return this.$route.query.isEdit === 'true'
    },
    routeData() {
      if (this.$route.query.data) {
        try {
          return JSON.parse(
            decodeURIComponent(this.$route.query.data)
          )
        } catch (e) {
          console.error('Failed to parse route data:', e)
          return null
        }
      }
      return null
    }
  },
  watch: {},
  mounted() {
    this.getProjectBaseInfoList()
    if (this.pkid && this.routeData) {
      this.basicForm = JSON.parse(
        JSON.stringify(this.routeData)
      )
      if (
        this.routeData.resourceFileInfos &&
        this.routeData.resourceFileInfos.length
      ) {
        this.fileList =
          this.routeData.resourceFileInfos.map((item) => {
            return {
              ...item,
              url: `${STATIC_FILE_URL}${item.filePath}`
            }
          })

        if (this.isDetail) {
          this.previewImageList = this.fileList.map(
            (item) => item.url
          )
        }

        this.uploadFileList = JSON.parse(
          JSON.stringify(this.fileList)
        )
      }
    }
  },
  methods: {
    getProjectBaseInfoList() {
      this.loading = true
      queryConstructionProject({
        pageIndex: 1,
        pageSize: 9999
      }).then((res) => {
        if (res.success) {
          this.projectBaseInfoOptions = res.data.list
        }
        this.loading = false
      })
    },
    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file) {
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    },

    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          // Handle date formatting
          // if (this.basicForm.buildEndTime) {
          //   this.basicForm.buildEndTime = dayjs(
          //     this.basicForm.buildEndTime
          //   ).format('YYYY-MM-DD')
          // } else {
          //   this.basicForm.buildEndTime = ''
          // }

          if (this.basicForm.planBuildTime) {
            this.basicForm.planBuildTime = dayjs(
              this.basicForm.planBuildTime
            ).format('YYYY-MM-DD')
          } else {
            this.basicForm.planBuildTime = ''
          }

          if (this.basicForm.actuallyBuildTime) {
            this.basicForm.actuallyBuildTime = dayjs(
              this.basicForm.actuallyBuildTime
            ).format('YYYY-MM-DD')
          } else {
            this.basicForm.actuallyBuildTime = ''
          }

          const currentUpload = this.uploadFileList.filter(
            (i) => !i.pkid
          )
          const isUploadImage = this.uploadFileList
            .filter((i) => i.pkid)
            .map((item) => item.pkid)

          const uploadPromises = currentUpload.map(
            (file) => {
              const image = new FormData()
              image.append('file', file)
              return uploadFileById(image)
            }
          )

          Promise.all(uploadPromises)
            .then((results) => {
              const allSuccess = results.every(
                (res) => res.success
              )

              if (!allSuccess) {
                this.$message.error('部分图片上传失败')
                return
              }

              let imageArr = results.map(
                (item) => item.data
              )
              this.basicForm.picture = imageArr
                .concat(isUploadImage)
                .join(',')

              addCenterPlatform(this.basicForm).then(
                (res) => {
                  if (res.success) {
                    this.$message.success(
                      this.pkid ? '编辑成功' : '保存成功'
                    )
                    this.$router.push({
                      path: '/dataManagement/technologyManagement/centerPlatform/list',
                      query: { refresh: Date.now() }
                    })
                  } else {
                    this.$message.error(res.message)
                  }
                }
              )
            })
            .catch((err) => {
              this.loading = false
              this.$message.error('图片上传出错')
              console.error(err)
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }
  .el-icon-plus {
    margin-top: 50px;
    .icon-text {
      color: #999;
      font-size: 16px;
      margin-top: 10px;
    }
  }
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}
</style>
